<template>
  <main-content
    title="配置商品"
    back
  >
    <el-form
      ref="configureGoodsFormRef"
      :model="configureGoodsForm"
      :rules="configureGoodsFormRules"
      :label-width="120"
    >
      <el-form-item
        label="商品名称"
        prop="name"
        class="common-form-width"
      >
        <el-input
          v-model.trim="configureGoodsForm.name"
          placeholder="请输入商品名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        label="商品图片"
        prop="thumbnailUrl"
      >
        <upload
          v-model:model-value="configureGoodsForm.thumbnailUrl"
          :is-add-first-text="true"
          :limit="10"
          list-type="picture-card"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </upload>
      </el-form-item>

      <el-form-item
        label="商品分类"
        prop="categoryId"
        class="common-form-width"
      >
        <el-select
          v-model="configureGoodsForm.categoryId"
          placeholder="请选择商品分类"
          clearable
        >
          <el-option
            v-for="item in goodsCateList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        class="long-character-label"
        label="可用于支付的代币名称"
        prop="showCurrencyNames"
      >
        <el-tag>
          {{ getCurrencyLabel(mallConfig.currencyId) }}
        </el-tag>
      </el-form-item>

      <el-form-item
        class="common-form-width"
        label="商品原价"
        prop="originalPrice"
      >
        <el-input v-model="configureGoodsForm.originalPrice">
          <template #append>
            元
          </template>
        </el-input>
      </el-form-item>

      <!-- <goods-exchange-limit 
        v-model:limit-time-type="configureGoodsForm.limitTimeType" 
        v-model:product-limit="configureGoodsForm.productLimit"
      /> -->
      <el-form-item class="long-character-label common-form-width" label="兑换限制（件/人）" prop="productLimit">
        <el-input v-model="configureGoodsForm.productLimit" type="number" placeholder="兑换限制" :min="1" :max="99999999">
          <template #append>
            件/人
          </template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="排序"
        prop="sort"
      >
        <el-input-number
          v-model="configureGoodsForm.sort"
          :step="1"
          step-strictly
          :min="1"
          :max="99999999"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="onlineStatus"
          active-text="上架"
          inactive-text="下架"
          inline-prompt
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
      <el-form-item>
        <template #label>
          <div class="audit-label">
            <span>商品审核</span>
            <el-popover
              placement="bottom"
              :width="200"
              trigger="hover"
              content="开启后，用户兑换该商品，需要经过您的审核，审核通过的用户可以领取，审核拒绝则领取失败"
            >
              <template #reference>
                <span class="question-icon">?</span>
              </template>
            </el-popover>
          </div>
        </template>
        <div>
          <el-switch
            v-model="verifyFlag"
            active-text="开启"
            inactive-text="关闭"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
          />
          <div class="tips">
            开启后,及时前往“订单管理-审核订单”进行审核
          </div>
        </div>
      </el-form-item>
      <el-form-item
        v-if="configureGoodsForm.type == 'recharge'"
        prop="rechargeAccountRegexId"
        label="充值账号名称"
      >
        <el-select
          v-model="configureGoodsForm.rechargeAccountRegexId"
          placeholder="请选择"
          @change="rechargeAccountRegexChange"
        >
          <el-option
            v-for="i in rechargeAccountRegexList"
            :key="i.id"
            :value="i.id"
            :label="i.name"
          />
        </el-select>
        <span style="margin-left: 4px;color: #999;">正则：{{ configureGoodsForm.rechargeAccountRegex }}</span>
      </el-form-item>

      <el-form-item
        label="商品规格"
        prop="products"
        class="common-form-width"
      >
        <el-row class="form-inline-row">
          <el-form-item>
            <el-select
              placeholder="请选择规格"
              clearable
              @change="selectProduct"
            >
              <el-option
                v-for="item in productsOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-table :data="configureGoodsForm.products">
          <el-table-column
            label="规格名称"
            prop="name"
            width="180"
          >
            <template #header>
              <span style="color: red">* </span>规格名称
            </template>
            <template #default="scope">
              <el-input
                v-model.trim="scope.row.name"
                class="product-input"
                placeholder="请输入规格名称"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="规格图片"
            prop="thumbnailUrl"
            width="180"
          >
            <template #header>
              <span style="color: red">* </span>规格图片
            </template>
            <template #default="scope">
              <upload
                v-model:model-value="scope.row.thumbnailUrl"
                list-type="picture-card"
                :limit="1"
              >
                <template #default>
                  <el-icon>
                    <plus />
                  </el-icon>
                </template>
              </upload>
            </template>
          </el-table-column>
          <el-table-column
            label="供货价(元)"
            prop="costPrice"
            min-width="120"
          >
            <template #default="scope">
              {{
                scope.row.costPrice
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="市场价(元)"
            prop="originalPrice"
            min-width="120"
          >
            <template #default="scope">
              {{
                isNaN(scope.row.originalPrice)
                  ? scope.row.originalPrice
                  : scope.row.originalPrice / 100
              }}
            </template>
          </el-table-column>

          <el-table-column
            label="售价"
            width="350"
          >
            <template #header>
              <span style="color: red">* </span>售价
            </template>
            <template #default="scope">
              <div style="display: flex; flex-wrap: nowrap">
                <el-input
                  v-model="scope.row.payOfCurrencyCount"
                  class="product-input"
                  type="number"
                >
                  <template #append>
                    积分
                  </template>
                </el-input>
                <div style="width: 10px" />
                <el-input
                  v-model="scope.row.payPrice"
                  class="product-input"
                  type="number"
                  :disabled="isEmpty(mallConfig.payConfigId)"
                >
                  <template #append>
                    元
                  </template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="规格剩余库存"
            prop="stock"
            min-width="120"
          />
          <el-table-column
            label="商家规格预占剩余库存"
            prop="beforeStock"
            min-width="120"
          >
            <template #header>
              商家规格预占<br>
              剩余库存
            </template>
          </el-table-column>
          <el-table-column
            label="库存增减量"
            prop="addOrDeductionStockCount"
            width="180"
          >
            <template #header>
              <span style="color: red">* </span>库存增减量
            </template>
            <template #default="scope">
              <el-input
                v-model="scope.row.addOrDeductionStockCount"
                class="product-input"
                placeholder="请输入库存增减量"
                type="number"
                min="1"
              />
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-switch
                v-model="scope.row.onlineStatus"
                :active-value="1"
                :inactive-value="0"
                inline-prompt
                active-text="上架"
                inactive-text="下架"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="deleteProduct(scope.row, scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item
        label="使用说明"
        prop="description"
      >
        <div class="desc-text">
          <!-- <el-input v-model="configureGoodsForm.description" type="textarea" :rows="5" placeholder="使用说明" /> -->
          <rich-editor
            :initial-value="initialDescText"
            scroll-selector=".body"
            id-name="desc"
            @change="handleDescTextChange"
          />
        </div>
      </el-form-item>

      <el-form-item
        label="商品介绍"
        prop="detailText"
      >
        <div
          v-if="!flag"
          class="text-box"
          v-html="formatStr(configureGoodsForm.detailText)"
        />
        <rich-editor
          v-if="flag"
          :initial-value="initialDetailText"
          scroll-selector=".body"
          @change="handleDetailTextChange"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="cancel">
          取消
        </el-button>
        <el-button
          v-loading="saveLoading"
          type="primary"
          @click="save"
        >
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </main-content>
</template>

<script lang="ts" setup>
import { useGetGoodsCategory } from "@/views/pointsMall/compositions/useGetGoodsCategory";
import { addGoods, getStoreGoodsDetail } from "@/api/pointsMall";
import { IStoreGoodsDetail, IStoreProductRow } from "@/api/modules/pointsMall";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import { FormRules, FormInstance } from "element-plus";
import { useGetCurrencyType } from "@/views/pointsMall/compositions/useGetCurrencyType";
import {
  positiveInteger_0,
  positiveNumber_decimal$2,
} from "@/utils/commonRegexp";
import { useCrossPage } from "@/compositions/crossPage/useCrossPage";
import sysConfigApi from "@/api/sysConfigApi";

const router = useRouter();
const route = useRoute();
const { goodsCateList } = useGetGoodsCategory();
const { mallConfig } = useMallConfig();
//商品图文是否仅仅预览
const flag = ref(true)

// 规格选项
const productsOptions = ref<IStoreProductRow[]>([]);
const initialDetailText = ref("");
const initialDescText = ref('')
const configureGoodsFormRef = ref<FormInstance>();
const configureGoodsForm = reactive<IStoreGoodsDetail>({
  mallId: mallConfig.value.id,
  id: undefined,
  storeGoodsId: undefined,
  name: "",
  thumbnailUrl: [],
  categoryId: undefined,
  showCurrencyNames: "",
  showMinPrice: undefined,
  showMinCurrencyPrice: undefined,
  limitTimeType: "",
  productLimit: undefined,
  products: [],
  description: "",
  detailText: "",
  sort: 1,
  stock: 0,
  originalPrice: "",
  onlineStatus: null,
  bannerImages: "",
  rechargeAccountRegex: "",
  rechargePlaceHolder: "",
  rechargeAccountRegexId: undefined
});
const onlineStatus = ref(1); //商品是否上架

const verifyFlag = ref(0);//商品审核开启

const configureGoodsFormRules = reactive<FormRules>({
  name: [ { message: "请输入商品名称", required: true, trigger: "blur" } ],
  thumbnailUrl: [
    { message: "请上传商品图片", required: true, trigger: "blur" },
  ],
  categoryId: [
    { message: "请选择商品分类", required: true, trigger: "change" },
  ],
  // showCurrencyNames: [{
  //   required: true,
  //   validator(rule, val, callback) {
  //     if (!val) {
  //       callback('请选择可用于支付的代币名称')
  //     } else {
  //       callback()
  //     }
  //   },
  // }],
  combinedProductPrice: [
    {
      required: true,
      validator(rule, val, callback) {
        if (
          isEmpty(configureGoodsForm.showMinCurrencyPrice) ||
          isEmpty(configureGoodsForm.showMinPrice)
        ) {
          callback(new Error("商品价格是必填的"));
          configureGoodsFormRef.value?.clearValidate([
            "showMinCurrencyPrice",
            "showMinPrice",
          ]);
        } else {
          callback();
        }
      },
    },
  ],
  showMinCurrencyPrice: [
    {
      required: true,
      trigger: "blur",
      validator(rule, val, callback) {
        if (
          !positiveInteger_0.test("" + configureGoodsForm.showMinCurrencyPrice)
        ) {
          callback(new Error("商品售价【积分】只能0或正整数"));
        } else if (
          Number(configureGoodsForm.showMinCurrencyPrice) > 9999999999
        ) {
          callback(new Error("超过上限【99,9999,9999】"));
        } else {
          configureGoodsFormRef.value?.clearValidate([
            "showMinCurrencyPrice",
            "combinedProductPrice",
          ]);
          callback();
        }
      },
    },
  ],
  showMinPrice: [
    {
      required: true,
      trigger: "blur",
      validator(rule, val, callback) {
        if (
          !positiveNumber_decimal$2.test("" + configureGoodsForm.showMinPrice)
        ) {
          callback(new Error("商品售价【现金】需大于0且仅保留2位小数"));
        } else if (Number(configureGoodsForm.showMinPrice) > 9999999999) {
          callback(new Error("超过上限【99,9999,9999】"));
        } else {
          configureGoodsFormRef.value?.clearValidate([
            "showMinPrice",
            "combinedProductPrice",
          ]);
          callback();
        }
      },
    },
  ],
  sort: [
    {
      message: "请输入排序",
      required: true,
      trigger: "change",
    },
  ],
  productLimit: [
    {
      message: "请输入兑换限制",
      required: true,
      trigger: "blur",
    },
    {
      message: "兑换限制仅能为正整数",
      validator(rule, val, callback) {
        if (!/^[1-9]*[1-9][0-9]*$/.test(val)) {
          callback(new Error("兑换限制仅能为正整数"));
        } else {
          callback();
        }
      },
    },
    {
      message: "超过上限【99,9999,9999】",
      validator(rule, val, callback) {
        if (Number(val) > 9999999999) {
          callback(new Error("超过上限【99,9999,9999】"));
        } else {
          callback();
        }
      },
    },
  ],
  products: [
    {
      message: "请添加规格",
      required: true,
      validator(rule, val, callback) {
        if (!configureGoodsForm.products.length) {
          callback(new Error("请添加商品规格"));
        } else {
          callback();
        }
      },
    },
  ]
});

// 可用于支付的代币名称
const { getCurrencyLabel } = useGetCurrencyType();

const selectProduct = (val: number) => {
  const target = productsOptions.value.find((item) => item.id === val);
  if (target) {
    const costPrice = target.costPrice ? target.costPrice / 100 : (target.payPrice ?? 0) / 100
    configureGoodsForm.products.push({
      ...target,
      costPrice: costPrice,
      //填充初始积分
      payOfCurrencyCount: Number((costPrice * (target.exchangeRatio ? Number(target.exchangeRatio) : 0)).toFixed(4)),
      payPrice: 0,
    });
  }
};

const handleDetailTextChange = ({ innerHTML }: { innerHTML: string }) => {
  configureGoodsForm.detailText = innerHTML;
};
const handleDescTextChange = ({ innerHTML }: { innerHTML: string }) => {
  configureGoodsForm.description = innerHTML;
};

const deleteProduct = (row: IStoreProductRow, index: number) => {
  configureGoodsForm.products.splice(index, 1);
};

const isEmpty = (val: any) => {
  return val === null || val === undefined || val === "";
};

const createErrorMessage = (result: boolean, message: string) => {
  return {
    result,
    message,
  };
};

const checkManullyForm = () => {
  for (let i = 0; i < configureGoodsForm.products.length; i++) {
    const product = configureGoodsForm.products[i];
    if (isEmpty(product.name)) {
      return createErrorMessage(false, `请输入规格表第${i + 1}行的规格名称`);
    }

    if (isEmpty(product.thumbnailUrl)) {
      return createErrorMessage(false, `请上传规格表第${i + 1}行的规格图片`);
    }

    if (!/^(0|[1-9][0-9]*)$/.test("" + product.payOfCurrencyCount)) {
      return createErrorMessage(
        false,
        `请输入规格表第${i + 1}行的售价（积分），且只能为0或正整数`
      );
    }

    if (Number(product.payOfCurrencyCount) > 9999999999) {
      return createErrorMessage(
        false,
        `规格表第${i + 1}行的售价（积分），超过上限【99,9999,9999】`
      );
    }

    if (!/(^[0-9]+$)|(^[0-9]+\.[0-9]{1,2}$)/.test("" + product.payPrice)) {
      return createErrorMessage(
        false,
        `规格表第${i + 1}行的售价（现金）不正确，不能为负数且仅保留2位小数`
      );
    }

    if (Number(product.payPrice) > 9999999999) {
      return createErrorMessage(
        false,
        `规格表第${i + 1}行的售价（现金），超过上限【99,9999,9999】`
      );
    }

    if (isEmpty(product.addOrDeductionStockCount)) {
      return createErrorMessage(
        false,
        `规格表第${i + 1}行的库存增减量不能为空`
      );
    }

    if (product.addOrDeductionStockCount > product.beforeStock) {
      return createErrorMessage(
        false,
        `规格表第${i + 1}行的库存增减量不能大于商家规格预占剩余库存`
      );
    }

    if (product.addOrDeductionStockCount < 1) {
      return createErrorMessage(
        false,
        `规格表第${i + 1}行的库存增减量不能小于1`
      );
    }
    if (product.payOfCurrencyCount == 0 && product.payPrice == 0) {
      return createErrorMessage(
        false,
        `规格表第${i + 1}行的售价（积分)和售价（现金）不能同时为0`
      );
    }
  }

  return createErrorMessage(true, "");
};

const formatData = () => {
  const _configureGoodsForm = JSON.parse(
    JSON.stringify({ ...configureGoodsForm })
  ) as unknown as IStoreGoodsDetail;

  _configureGoodsForm.storeGoodsId = configureGoodsForm.id;
  _configureGoodsForm.showCurrencyNames = getCurrencyLabel(
    mallConfig.value.currencyId
  );
  _configureGoodsForm.stock = configureGoodsForm.products.reduce(
    (total, current) => total + current.stock,
    0
  );
  _configureGoodsForm.showMinPrice =
    parseInt((Number(configureGoodsForm.showMinPrice) * 100).toFixed(2).slice(0, -3)); // 后端接收的单位为分
  _configureGoodsForm.originalPrice =
    parseInt((Number(configureGoodsForm.originalPrice) * 100).toFixed(2).slice(0, -3)); // 后端接收的单位为分
  _configureGoodsForm.products.forEach((product) => {
    product.storeProductId = product.id;
    product.payPrice = parseInt((product.payPrice * 100).toFixed(2).slice(0, -3)); // 后端接收的单位为分
    product.costPrice = parseInt((product.costPrice * 100).toFixed(2).slice(0, -3)); //供货价 后端接收的单位为分
  });

  //商品是否上架
  _configureGoodsForm.onlineStatus = onlineStatus.value;
  //商品审核开关
  _configureGoodsForm.verifyFlag = verifyFlag.value;

  //多张图片作为轮播图
  _configureGoodsForm.bannerImages = configureGoodsForm.thumbnailUrl
    ? configureGoodsForm.thumbnailUrl.toString()
    : "";
  //处理第一张封面图
  _configureGoodsForm.thumbnailUrl = Array.isArray(
    configureGoodsForm.thumbnailUrl
  )
    ? configureGoodsForm.thumbnailUrl[0]
    : configureGoodsForm.thumbnailUrl;

  return _configureGoodsForm;
};

const saveLoading = ref(false);
const save = async () => {
  configureGoodsFormRef.value?.validate(async (valid, fields) => {
    if (valid) {
      const checkResult = checkManullyForm();

      if (!checkResult.result) {
        ElMessage.warning(checkResult.message);
        return;
      }

      const _configureGoodsForm = formatData();
      //判断商品是否可以上架
      if (_configureGoodsForm.onlineStatus) {
        const flag = _configureGoodsForm.products.some(
          (item) => item.stock === 0
        );
        if (flag) {
          return ElMessage.warning("存在库存不足的规格!");
        }
      }

      saveLoading.value = true;

      const rs = await addGoods(_configureGoodsForm);
      saveLoading.value = false;

      if (rs.code === 30001) {
        ElMessageBox.confirm("未设置支付配置", "提示", {
          confirmButtonText: "前往设置",
          cancelButtonText: "取消",
        })
          .then(() => {
            const hrefArray = location.href.split("/");
            hrefArray.splice(hrefArray.length - 1, 1, "mall_setting");
            window.open(hrefArray.join("/"));
          })
          .catch(() => {
            // cancel
          });
        return;
      }

      if (rs.code === 200) {
        ElMessage.success("保存成功");
        storeEvent("refreshList") // TODO 测试中
        router.back();
      }
    } else {
      console.log(fields);
    }
  });
};
const cancel = () => {
  router.back();
};

const _getStoreGoodsDetail = async () => {
  const rs = await getStoreGoodsDetail({ id: route.query.id as string, mallId: mallConfig.value.id });

  if (rs.code === 200) {
    if (rs.payload) {
      Object.keys(rs.payload).forEach((key) => {
        configureGoodsForm[key] = rs.payload?.[key];
      });
      configureGoodsForm.originalPrice =
        Number(configureGoodsForm.originalPrice) / 100;
      configureGoodsForm.products = [];
      productsOptions.value = rs.payload.products.map((item) => ({
        ...item,
        thumbnailUrl: item.thumbnailUrl ?? "", // upload组件需要
        payOfCurrencyCount: 0,

      }));
      flag.value = canEdit(configureGoodsForm.detailText)
      initialDetailText.value = rs.payload.detailText ?? "";
      initialDescText.value = configureGoodsForm.description ?? ''

      //获取直充配置
      if (configureGoodsForm.type == 'recharge') {
        getRechargeAccountRegexList()
      }
    }
  }
};

const { storeEvent } = useCrossPage("pointsMall", {});
//替换富文本字符
const formatStr = (str) => {
  return str.replaceAll(/\\n/g, '')
}

//判断富文本是否可以编辑
const canEdit = (text) => {
  if (text && typeof text == 'string') {
    if (text.startsWith('<style>')) {
      return false
    }
    return true

  }
  return true
}

/***直充类配置 */
interface IRechargeAccountRegexItem {
  id: number, placeHolder: string, regex: string, name: string
}
const rechargeAccountRegexList = ref<IRechargeAccountRegexItem[]>([])
//获取直充配置
const getRechargeAccountRegexList = async () => {
  const res = await sysConfigApi.getRegexList({})
  if (res.code == 200) {
    rechargeAccountRegexList.value = res.payload
  }
}

const rechargeAccountRegexChange = (val: number | null) => {
  if (val) {
    const el = rechargeAccountRegexList.value.find(i => i.id == val)
    if (el) {
      configureGoodsForm.rechargePlaceHolder = el.placeHolder
      configureGoodsForm.rechargeAccountRegex = el.regex
    }
  }
}

onMounted(() => {
  if (route.query.id) {
    _getStoreGoodsDetail();
  }
});
</script>

<style scoped lang="scss">
@use "@/components/goodsCenter/styles/common.scss";

.form-inline-row {
  margin-bottom: 5px;
}

.line-input {
  display: flex;
  flex-wrap: nowrap;
}

.long-character-label:deep(.el-form-item__label) {
  height: unset;
  text-align: right;
  line-height: 1.5;
}

.vertical-form-content:deep(.el-form-item__content) {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
}

// .product-limit-form-wrapper {
//   .product-limit:not(:last-child) {
//     margin-bottom: 10px;
//   }

//   .product-limit:deep(.el-select) {
//     width: 80px;
//     margin-right: 10px;
//     .el-input {
//       width: 80px;
//     }
//   }

//   .product-limit:deep(.el-input) {
//     width: 210px;
//   }
// }

.currency-type-tag {
  margin-right: 5px;
}

.product-input {
  width: 150px !important;
}

.audit-label {
  display: flex;
  align-items: center;
}

.question-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 12px;
  height: 12px;
  margin-left: 4px;
  font-size: 10px;
  color: var(--el-text-color-regular);
  border-radius: 50%;
  border: 1px solid var(--el-text-color-regular);
}

.tips {
  font-size: 12px;
  color: #999;
}

.text-box {
  overflow-y: auto;
  height: 54vh;
  width: 100%;
  border: 1px solid var(--el-border-color);
}
</style>
